<template>
  <div class="matlab" @click="hideToolbar">
    <div v-show="$store.state.functions.searching" id="darken" />
    <toolbar />
    <navigation
      :style="{ marginTop: $store.getters['matlab/getMarginTop'] }"
      @jumpFolder="jumpFolder"
    />

    <div class="editor">
      <div class="left-out">
        <div
          id="resize1000"
          class="resize-left"
          :class="{
            resize1: !isLeftOpen,
          }"
          @mousedown="resizeLeftDown"
        />
        <div class="resizeLine" />
        <div
          v-show="isLeftOpen"
          class="left"
          :style="{ height: $store.getters['matlab/getContentHeight'] }"
        >
          <div
            class="module"
            :class="{
              nhalf: isFileOpen && isWorkOpen,
              max: isFileOpen && !isWorkOpen,
              on: !isFileOpen,
            }"
          >
            <div class="module-title dis-flex space-between">
              <icon-caret v-model="isFileOpen" />
              <label>当前文件夹</label>

              <icon-more
                trigger="click"
                :dropdown-items="$store.getters['matlab/isRootFolder'] ? dropdownRootItems : dropdownItems"
                :click-functions="clickFunctions"
              />
            </div>

            <div v-show="isFileOpen" id="folderTreeWarpper" class="module-content">
              <matlab-folder-tree ref="folderTree" />
            </div>
          </div>

          <div
            class="module"
            :class="{
              shalf: isFileOpen && isWorkOpen,
              max: !isFileOpen && isWorkOpen,
            }"
          >
            <div
              class="resize-bottom"
              :class="{
                resize1: !isWorkOpen,
              }"
              @mousedown="resizeWorkDown"
            />
            <div class="resize-line" />
            <div class="module-title down dis-flex space-between">
              <icon-caret v-model="isWorkOpen" />
              <label>工作区</label>
              <!-- <i class="el-icon-more"></i> -->
              <i />
              <!-- 填入空白i, 方便使用space between来布局 -->
            </div>

            <div v-show="isWorkOpen" id="workWarpper" class="module-content down">
              <variable-explorer :variables="variables" />
            </div>
          </div>
        </div>
        <div v-show="!isLeftOpen" class="left hidden">
          <i class="el-icon-caret-right" @click="isLeftShow" />
        </div>
      </div>
      <div
        class="right"
        :class="{
          max: !isLeftOpen,
        }"
        :style="{ height: $store.getters['matlab/getContentHeight'] }"
      >
        <div
          id="editor1"
          class="module"
          :class="{
            nhalf: isEditorOpen && isCommandOpen,
            max: isEditorOpen && !isCommandOpen,
            on: !isEditorOpen,
          }"
        >
          <div class="module-title dis-flex space-between">
            <icon-caret v-model="isEditorOpen" />
            <label>编辑器</label>

            <i />
          </div>

          <div v-show="isEditorOpen" v-if="refresh" class="module-content">
            <matlab-editor-tabs />
          </div>
        </div>
        <div
          class="module"
          :class="{
            shalf: isCommandOpen && isEditorOpen,
            max: isCommandOpen && !isEditorOpen ,
          }"
        >
          <div
            class="resize-bottom"
            :class="{
              resize1: !isCommandOpen,
            }"
            @mousedown="resizeCommandDown"
          />
          <div class="resize-line" />
          <div class="module-title down dis-flex space-between">
            <icon-caret v-model="isCommandOpen" />
            <label>运行窗口</label>

            <i />
          </div>

          <!-- <div v-show="isCommandOpen" class="module-content"> -->
          <!-- <terminal-window></terminal-window> -->
          <!-- <notebook-window></notebook-window> -->
          <div v-show="isCommandOpen" id="runWarpper" class="module-content down" style="background: #FAFAFA">
            <run-window :variables="variables" />
          </div>
        </div>
      </div>
    </div>

    <browse-files
      ref="browse"
      name="browse"
      :is-show="isBrowseShow"
      :title="browseType === 'folder' ? '选择路径' : '打开文件'"
      :type="browseType"
      @callback="openBrowse"
    />

    <search-file ref="searchFile" title="转至文件" />

    <choose-var-dialog />
    <draw-list-dialog />
    <div v-for="(item,index) in matlabImgJson" id="newFile" :key="index">
      <matlab-img-dialog :id="index" />
    </div>
    <base64-img-dialog />
  </div>
</template>

<script>
/**
 * title: "matlab主页"
 * name: "Matlab"
 * path: "/"
 */
import Toolbar from './plugins/toolbar/Toolbar.vue';
import Navigation from './plugins/Navigation.vue';
// import FolderTree from './plugins/FolderTree.vue';
import MatlabFolderTree from './plugins/MatlabFolderTree.vue';
import IconMore from '@/components/icon/IconMore.vue';
import IconCaret from '@/components/icon/IconCaret.vue';
import MatlabEditorTabs from './plugins/MatlabEditorTabs.vue';
import BrowseFiles from './plugins/BrowseFiles.vue';
import SearchFile from './plugins/SearchFile.vue';
import MatlabImgDialog from './plugins/dialog/MatlabImgDialog.vue';
import Base64ImgDialog from './plugins/dialog/Base64ImgDialog.vue';
import DrawListDialog from './plugins/dialog/DrawListDialog.vue';
import ChooseVarDialog from './plugins/dialog/ChooseVarDialog.vue';
// import TerminalWindow from './plugins/TerminalWindow.vue';
import VariableExplorer from './plugins/VariableExplorer.vue';
// import NotebookWindow from './plugins/NotebookWindow';
import RunWindow from './plugins/RunWindow';
import { debounce } from 'lodash-es';
import { saveWorkspace } from '@/utils/variable';
import Driver from 'driver.js';
import 'driver.js/dist/driver.min.css';
import { createFunctionLibrary } from '@/api/userProjectLibrary';
var _this = {};
export default {
  name: 'Matlab',
  components: {
    Navigation,
    Toolbar,
    MatlabFolderTree,
    IconMore,
    IconCaret,
    MatlabEditorTabs,
    BrowseFiles,
    SearchFile,
    MatlabImgDialog,
    DrawListDialog,
    ChooseVarDialog,
    // TerminalWindow,
    // NotebookWindow,
    RunWindow,
    VariableExplorer,
    Base64ImgDialog
  },
  data: () => ({
    input3: '',
    select: '',
    editorContent: '',
    isLeftOpen: true,
    isFileOpen: true,
    isWorkOpen: true,
    isEditorOpen: true,
    isCommandOpen: true,
    isResizing: false,
    isLeftResizing: false,
    isRightResizing: false,
    isMouseDown: false,
    isMouseUp: true,
    offsetHeight: '',
    clientX: '',
    clientY: '',
    dropdownItems: [
      { type: 'buildFolder', label: '创建文件夹' },
      { type: 'buildFile', label: '创建脚本' }
    ],
    dropdownRootItems: [{ type: 'buildRootFolder', label: '创建工程' }],
    isBrowseShow: false,
    browseType: '',
    refresh: true
  }),
  provide() {
    return {
      setBread: this.setBread,
      searchFiles: this.searchFiles
    };
  },
  computed: {
    variables: function() {
      return this.$store.getters['matlab/getProcessedVariables'];
    },
    matlabImgJson: function() {
      return this.$store.state.matlab.matlabImgJson;
    }
  },
  watch: {
    isCommandOpen: 'check'
  },
  beforeCreate() {
    _this = this;
  },
  mounted() {
    this.newUserIntro();
    this.$store.dispatch('matlab/getAll');
    window.addEventListener('resize', this.resizeWindow);
    document.addEventListener('keydown', this.saveEvent);
    window.addEventListener('mousemove', this.mouseMove);
    window.addEventListener('mouseup', this.mouseUp);
    const resizeObserver = new ResizeObserver(this.onResize);
    resizeObserver.observe(document.getElementById('editor1'));
  },
  destroyed() {
    window.removeEventListener('resize', this.resizeWindow);
    document.removeEventListener('keydown', this.saveEvent);
    window.removeEventListener('mousemove', this.mouseMove);
    window.removeEventListener('mouseup', this.mouseUp);
  },
  methods: {
    onResize() {
      this.refresh = false;
      this.$nextTick(() => {
        this.refresh = true;
      });
    },
    newUserIntro() {
      if (localStorage.getItem('firstOpenIndexPage') !== null || this.$store.state.user.lastLogin !== 'firstlogin') { // 已经不是第一次了
        return;
      }
      // 第一次进入时创建runtime库
      createFunctionLibrary({ libraryName: this.$store.state.user.userprefix + 'runtime', desc: 'USER RUNTIME ' + this.$store.state.user.email });
      localStorage.setItem('firstOpenIndexPage', false);

      const driver = new Driver({
        className: 'driver-class',
        animate: true,
        opacity: 0.3,
        padding: 0,
        allowClose: false,
        overlayClickNext: false,
        doneBtnText: '知道了',
        closeBtnText: '关闭',
        nextBtnText: '下一步',
        prevBtnText: '上一步',
        showButtons: true,
        keyboardControl: false,
        scrollIntoViewOptions: {
          block: 'end'
        }
      });
      const steps = [{
        element: '#toolbar',
        popover: {
          title: '菜单栏',
          description: '在此处探索天演平台的各项功能',
          position: 'bottom-center'
        }
      }, {
        element: '#folderTreeWarpper',
        popover: {
          title: '文件',
          description: '在此处创建并管理您的工程文件',
          position: 'right'
        }
      }, {
        element: '#editor1',
        popover: {
          title: '编辑器',
          description: '在此处进行您的代码编辑',
          position: 'bottom-center'
        }
      },
      {
        element: '#workWarpper',
        popover: {
          title: '变量',
          description: '在此处查看各变量信息',
          position: 'right'
        }

      }, {
        element: '#runWarpper',
        popover: {
          title: '命令行',
          description: '在此处输入命令并查看输出结果',
          position: 'top-center'
        },
        onNext: () => { this.$store.commit('setCollapse', false); }
      }, {
        element: '#sidebarButtonWarpper',
        popover: {
          title: '函数库',
          description: '点击此处，进入函数库管理您的云函数',
          position: 'right'
        },
        onPrevious: () => { this.$store.commit('setCollapse', true); },
        onNext: () => { this.$store.commit('setCollapse', true); }
      }, {
        element: '#mainBarHelp',
        popover: {
          title: 'wiki',
          description: '点击帮助按钮获取更多帮助信息',
          position: 'bottom'
        },
        onPrevious: () => { this.$store.commit('setCollapse', false); }
      }];
      driver.defineSteps(steps);
      driver.reset();
      driver.start();
    },
    check() {
      this.refresh = false;
      this.$nextTick(() => {
        this.refresh = true;
      });
    },
    isLeftShow() {
      this.isLeftOpen = true;
      document.getElementById('resize1000').style.width = '250px';
    },
    resizeLeftDown() {
      this.isResizing = true;
    },
    resizeWorkDown() {
      this.isLeftResizing = true;
    },
    resizeCommandDown() {
      this.isRightResizing = true;
    },
    mouseUp() {
      if (this.isLeftResizing || this.isRightResizing || this.isResizing) {
        this.isLeftResizing = false;
        this.isRightResizing = false;
        this.isResizing = false;
      }
    },
    mouseMove(e) {
      if (this.isLeftResizing || this.isRightResizing || this.isResizing) {
        var y = document.body.offsetHeight;
        var mousey = e.clientY;
        var mousex = e.clientX;
        if (this.isLeftResizing) {
          if (y - mousey <= 100 && this.isWorkOpen) {
            this.isWorkOpen = false;
          } else if (y - mousey > 100 && !this.isWorkOpen) {
            this.isWorkOpen = true;
          } else if (mousey <= 150 && this.isFileOpen) {
            this.isFileOpen = false;
          } else if (mousey > 150 && !this.isFileOpen) {
            this.isFileOpen = true;
          }
        } else if (this.isRightResizing) {
          if (y - mousey <= 100 && this.isCommandOpen) {
            this.isCommandOpen = false;
          } else if (y - mousey > 100 && !this.isCommandOpen) {
            this.isCommandOpen = true;
          } else if (mousey <= 150 && this.isEditorOpen) {
            this.isEditorOpen = false;
          } else if (mousey > 150 && !this.isEditorOpen) {
            this.isEditorOpen = true;
          }
        } else if (this.isResizing) {
          if (mousex <= 100 && this.isLeftOpen) {
            this.isLeftOpen = false;
          } else if (mousex > 100 && !this.isLeftOpen) {
            this.isLeftOpen = true;
          }
        }
      }
    },
    resizeWindow: debounce((e) => {
      _this.$store.commit('matlab/resetInnerHeight');
    }, 300),
    hideToolbar(e) {
      this.$store.commit('matlab/setDownloadFile', 'shortly');
      var sp = document.getElementById('toolbar');
      if (sp) {
        if (!sp.contains(e.target)) {
          setTimeout(() => {
            this.$store.commit('matlab/isHideToolbar');
          }, 200);
        }
      }
    },
    saveEvent(e) {
      // js监听键盘ctrl+s快捷键保存
      if (
        e.keyCode === 83 &&
          (navigator.platform.match('Mac') ? e.metaKey : e.ctrlKey)
      ) {
        e.preventDefault();
        const store = this.$store.state.matlab;
        if (store.editorFiles.length) {
          if (store.isUploadFile) {
            this.$message.error('文件正在部署中...');
            return;
          }
          const file = store.editorFiles.find(
            (item) => item.id === store.editorFilesId
          );
          if (file && file.display === 'file' && file.editText !== file.editContent) {
            this.$store.dispatch('matlab/buildFiles', {
              type: 'update',
              id: file.id,
              text: file.editContent,
              path: file.path
            }).then((result) => {
              this.$message.success('保存成功');
            }).catch((err) => {
              this.$message.error('保存失败');
              console.error(err);
            });
          } else if (file && file.display === 'variable') {
            saveWorkspace(this.$store.state.matlab.variableArray);
          }
        }
      }
    },
    clickFunctions(type) {
      switch (type) {
        case 'buildRootFolder':
        case 'buildFolder':
        case 'buildFile':
          this.$store.commit('matlab/append', { nodeType: 'father', type });
          break;
      }
    },
    // 浏览文件夹或文件
    setBread(type) {
      this.browseType = type;
      this.isBrowseShow = true;
      this.$refs.browse.setTreeData();
    },
    // 打开文件夹或文件
    openBrowse(type, data) {
      // console.log('openBrowse', type, data);
      if (type === 'open') {
        if (this.browseType === 'folder') {
          this.$refs.folderTree?.setBread(data.data.id, data);
        } else {
          this.$store.dispatch('matlab/getFile', data);
        }
      }
      this.isBrowseShow = false;
    },
    jumpFolder(id) {
      this.$refs.folderTree?.setBread(id);
    },
    // 打开转至文件窗口
    searchFiles() {
      this.$refs.searchFile.show();
    },
    mutation() {
    }
  }

};
</script>

<style lang="scss" scoped>
.matlab {
  .editor {
    display: flex;
    .left-out {
      position: relative;
      overflow: hidden;
    }
    .left {
      position: absolute;
      top: 0;
      left: 0;
      right: 3px;
      height: 100%;
      display: flex;
      flex-direction: column;
      width: inherit;
      overflow: hidden;
      &.hidden {
        padding: 10px 2px;
        width: 15px;
      }
    }
    .right {
      height: 100%;
      display: flex;
      flex: 1;
      flex-direction: column;
      overflow: hidden;
      border-right: 1px solid #e5e5e5;
      &.max {
        height: calc(100vw - 30px);
      }
    }
  }
}
#darken{
  position: absolute;
  height:calc(100% - 28px );
  top: 28px;
  width: 100%;
  background: rgba(0,0,0,0.5);
  z-index: 99;
}
</style>
